import { createAlova } from "alova";
import VueHook from "alova/vue";
import { axiosRequestAdapter } from "@alova/adapter-axios";
import { ApiResponse } from "@/types";
import { getToken, removeToken, removeUserInfo } from "./storage";
import axios from "axios";
import { LoginResponse, User, Group, Task } from "@/types";
// 移除naive-ui message导入，使用console.error代替

// Mock数据服务
// 模拟用户数据
const mockUsers = {
  "yus": {
    user_id: 1,
    username: "yus",
    password: "123456",
    token: "mock-jwt-token-123456",
    expires_at: new Date(Date.now() + 86400000).toISOString() // 24小时后过期
  }
};

// 模拟任务分组数据
const mockGroups: Group[] = [
  {
    group_id: 1,
    name: "默认分组",
    is_default: true,
    task_count: 2,
    created_at: "2023-01-01T00:00:00Z"
  },
  {
    group_id: 2,
    name: "工作",
    is_default: false,
    task_count: 3,
    created_at: "2023-01-02T00:00:00Z"
  },
  {
    group_id: 3,
    name: "个人",
    is_default: false,
    task_count: 1,
    created_at: "2023-01-03T00:00:00Z"
  }
];

// 模拟任务数据
const mockTasks: Task[] = [
  {
    task_id: 1,
    group_id: 1,
    group_name: "默认分组",
    title: "完成项目文档",
    description: "撰写项目的技术文档和用户手册",
    is_important: true,
    is_my_day: true,
    status: 0,
    due_date: "2023-05-10T23:59:59Z",
    created_at: "2023-05-01T00:00:00Z"
  },
  {
    task_id: 2,
    group_id: 1,
    group_name: "默认分组",
    title: "准备周会汇报",
    description: "整理本周工作内容，准备周会汇报材料",
    is_important: false,
    is_my_day: true,
    status: 1,
    due_date: "2023-05-08T18:00:00Z",
    created_at: "2023-05-01T00:00:00Z",
    updated_at: "2023-05-07T10:00:00Z"
  },
  {
    task_id: 3,
    group_id: 2,
    group_name: "工作",
    title: "修复登录页面bug",
    description: "修复用户反馈的登录页面显示问题",
    is_important: true,
    is_my_day: false,
    status: 0,
    due_date: "2023-05-15T23:59:59Z",
    created_at: "2023-05-02T00:00:00Z"
  },
  {
    task_id: 4,
    group_id: 2,
    group_name: "工作",
    title: "开发新功能模块",
    description: "实现用户请求的新功能模块",
    is_important: true,
    is_my_day: false,
    status: 0,
    due_date: "2023-05-20T23:59:59Z",
    created_at: "2023-05-02T00:00:00Z"
  },
  {
    task_id: 5,
    group_id: 2,
    group_name: "工作",
    title: "参加技术分享会",
    description: "参加公司组织的技术分享会议",
    is_important: false,
    is_my_day: false,
    status: 2,
    due_date: "2023-05-05T14:00:00Z",
    created_at: "2023-05-03T00:00:00Z",
    updated_at: "2023-05-05T15:00:00Z"
  },
  {
    task_id: 6,
    group_id: 3,
    group_name: "个人",
    title: "健身锻炼",
    description: "去健身房进行30分钟的有氧运动",
    is_important: false,
    is_my_day: true,
    status: 0,
    due_date: "2023-05-08T20:00:00Z",
    created_at: "2023-05-04T00:00:00Z"
  }
];

// 提取URL路径部分的辅助函数
const getUrlPath = (url: string): string => {
  try {
    // 尝试解析URL
    const parsedUrl = new URL(url, 'http://localhost');
    return parsedUrl.pathname;
  } catch (e) {
    // 如果解析失败，直接返回原URL
    return url;
  }
};

// Mock API响应处理函数
const handleMockRequest = async (config: any): Promise<any> => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300));
  
  const fullUrl = config.url;
  const urlPath = getUrlPath(fullUrl);
  const method = config.method?.toLowerCase() || 'get';
  const data = config.data;
  const params = config.params || {};
  
  console.log('Mock request handling:', { 
    fullUrl, 
    urlPath, 
    method, 
    data, 
    params 
  });
  
  // 处理登录请求 - 简化URL匹配逻辑
  if (method === 'post' && urlPath.includes('/login')) {
    const { username, password } = data;
    const user = mockUsers[username as keyof typeof mockUsers];
    
    if (user && user.password === password) {
      const response: LoginResponse = {
        user_id: user.user_id,
        username: user.username,
        token: user.token,
        expires_at: user.expires_at
      };
      
      console.log('Mock login success:', response);
      
      return {
        code: 1,
        success: true,
        message: '登录成功',
        data: response
      };
    } else {
      throw new Error('用户名或密码错误');
    }
  }
  
  // 处理获取任务分组列表
  if (method === 'get' && urlPath.includes('/groups')) {
    console.log('Mock get groups:', mockGroups);
    return {
      code: 1,
      success: true,
      message: '获取成功',
      data: mockGroups
    };
  }
  
  // 处理创建任务分组
  if (method === 'post' && urlPath.includes('/groups')) {
    const newGroup: Group = {
      group_id: mockGroups.length + 1,
      name: data.name,
      is_default: false,
      task_count: 0,
      created_at: new Date().toISOString()
    };
    mockGroups.push(newGroup);
    
    console.log('Mock create group:', newGroup);
    
    return {
      code: 1,
      success: true,
      message: '创建成功',
      data: newGroup
    };
  }
  
  // 处理获取任务列表
  if (method === 'get' && urlPath.includes('/tasks')) {
    let filteredTasks = [...mockTasks];
    
    // 按分组筛选
    if (params.group_id) {
      filteredTasks = filteredTasks.filter(task => task.group_id === Number(params.group_id));
    }
    
    // 按状态筛选
    if (params.status !== undefined) {
      filteredTasks = filteredTasks.filter(task => task.status === Number(params.status));
    }
    
    // 按重要性筛选
    if (params.is_important !== undefined) {
      filteredTasks = filteredTasks.filter(task => task.is_important === Boolean(params.is_important));
    }
    
    // 按"我的一天"筛选
    if (params.is_my_day !== undefined) {
      filteredTasks = filteredTasks.filter(task => task.is_my_day === Boolean(params.is_my_day));
    }
    
    // 分页处理
    const page = params.page || 1;
    const page_size = params.page_size || 20;
    const start = (page - 1) * page_size;
    const end = start + page_size;
    const paginatedTasks = filteredTasks.slice(start, end);
    
    return {
      code: 1,
      success: true,
      message: '获取成功',
      data: {
        list: paginatedTasks,
        pagination: {
          page,
          page_size,
          total: filteredTasks.length
        }
      }
    };
  }
  
  // 处理创建任务
  if (method === 'post' && urlPath.includes('/tasks')) {
    const newTask: Task = {
      task_id: mockTasks.length + 1,
      group_id: data.group_id,
      group_name: mockGroups.find(g => g.group_id === data.group_id)?.name,
      title: data.title,
      description: data.description,
      is_important: data.is_important || false,
      is_my_day: data.is_my_day || false,
      status: 0,
      due_date: data.due_date,
      created_at: new Date().toISOString()
    };
    mockTasks.push(newTask);
    
    // 更新分组的任务计数
    const group = mockGroups.find(g => g.group_id === data.group_id);
    if (group) {
      group.task_count = (group.task_count || 0) + 1;
    }
    
    console.log('Mock create task:', newTask);
    
    return {
      code: 1,
      success: true,
      message: '创建成功',
      data: newTask
    };
  }
  
  // 默认返回404
  console.error('Mock API: No matching endpoint found for:', { urlPath, method });
  throw new Error('接口不存在');
};

// 创建axios实例
const axiosInstance = axios.create({
  // 使用配置的API基础URL
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8081',
  timeout: 10000,
});

// axios请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 使用真实API服务，关闭mock数据服务
const useMockOnly = false;

// axios响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    console.log('Axios success response:', response);
    const res = response.data as ApiResponse;
    if (res.code === 1 && res.success) {
      return res.data;
    } else {
      // 处理错误
      if (res.code === 10002) {
        // 用户未登录或token失效
        // 使用封装的方法清除本地存储
        removeToken();
        removeUserInfo();
        // 跳转到登录页 - 这里不使用window.location，避免与Vue Router冲突
        // 直接抛出错误，让上层处理导航
        console.error('登录已过期，请重新登录');
      }
      throw new Error(res.message || "请求失败");
    }
  },
  async (error) => {
    console.log('Axios error:', error);
    
    // 如果使用mock数据服务，直接调用mock处理函数
    if (useMockOnly) {
      try {
        const mockResponse = await handleMockRequest(error.config);
        console.log('Mock response:', mockResponse);
        // 返回正确的响应结构，让axios实例可以正确处理
        return { data: mockResponse.data };
      } catch (mockError: any) {
        console.error("Mock error:", mockError);
        console.error(`请求错误: ${mockError.message}`);
        throw mockError;
      }
    } else {
      // 实际API请求失败，直接抛出错误
      console.error(`请求错误: ${error.message}`);
      throw error;
    }
  }
);

// 创建Alova实例
const alovaInstance = createAlova({
  // VueHook用于Vue 3
  statesHook: VueHook,
  // 请求适配器，使用官方axios适配器
  requestAdapter: axiosRequestAdapter({
    axios: axiosInstance
  }),
  // 响应数据处理
  responded: {
    onSuccess: (response: any) => {
      console.log('Alova success response:', response);
      return response;
    },
    onError: (error: any) => {
      console.error('Alova error:', error);
      console.error(`请求错误: ${error.message}`);
      throw error;
    }
  }
});

export { axiosInstance, alovaInstance };
